const app = getApp();
var HEADER = "https://goodlife.gailaile.com/goodlife//app/";

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const toDate = number => {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return (Y + "-" + M + "-" + D + " " + H + ":" + m + ":" + S)
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

const getFloatStr = num => {
    num += '';
    num = num.replace(/[^0-9|\.]/g, ''); //清除字符串中的非数字非.字符
    if (/^0+/) //清除字符串开头的0
        num = num.replace(/^0+/, '');
    if (!/\./.test(num)) //为整数字符串在末尾添加.00
        num += '.00';
    if (/^\./.test(num)) //字符以.开头时,在开头添加0
        num = '0' + num;
    num += '00'; //在字符串末尾补零
    num = num.match(/\d+\.\d{2}/)[0];
    return num;
}

//封装微信ajax请求
/*
url -- 接口的名称 - 不用传固定的部分
data -- 传递的参数
callback -- 回调函数
method -- 请求的方式
isForm -- 是否是form提交
headerData -- 给请求头的参数
*/
const wxAjax = (url, method, data, callback, isForm, headerData) => {
    var type = "";
    var header = { 'content-type': 'application/json' };
    var token = wx.getStorageSync("token");
    var temp = HEADER + url;
    var userInfo = wx.getStorageSync("userInfo");
    if(!typeof(userInfo) || userInfo == ""){
        wx.switchTab({
            url: '../mine/mine',
        })
    }
    if (method == "POST" || method == "post") {
        type = "POST";
    } else {
        type = "GET";
    }
    if (token == "") {
        var timer = setInterval(function () {
            token = wx.getStorageSync("token");
            if (token != "") {
                clearInterval(timer);
            }
        }, 1000);
    }
    header = {
        'Authorization': "Bearer " + token
    }
    if (headerData && headerData != "") {
        header["shareToken"] = headerData;
    }
    if (isForm) {
        header["content-type"] = 'application/x-www-form-urlencoded';
    } else {
        header['content-type'] = 'application/json';
    }
    wx.showLoading({
        title: '正在加载....',
    })
    wx.request({
        url: temp, //仅为示例，并非真实的接口地址
        data: data,
        method: type,
        header: header,
        success: function (res) {
            wx.stopPullDownRefresh();
            wx.hideLoading();
            wx.hideNavigationBarLoading();
            if (!!callback) {
                callback(res);
            }
        },
        fail: function () {
            console.log('This is fail function')
        }
    })
}

/*  上传文件
    url -- 上传文件地址
    file -- 上传文件的本地文件地址
    filename -- 上传文件到服务器所接收的参数
    data -- 上传文件附加的参数
    callback -- 回调函数
*/
const upload = (url, file, filename, data, callback) => {
    var type = "POST";
    var header = {};
    var token = wx.getStorageSync("token");
    var temp = HEADER + url;
    if (token == "") {
        var timer = setInterval(function () {
            token = wx.getStorageSync("token");
            if (token != "") {
                clearInterval(timer);
            }
        }, 1000);
    }
    header = {
        'content-type': 'multipart/form-data;application/json;charset=utf-8',
        'Authorization': "Bearer " + token
    }
    wx.uploadFile({
        url: temp, //仅为示例，非真实的接口地址
        filePath: file,
        name: filename,
        header: header,
        formData: data,
        success: function (res) {
            if (!!callback) {
                if (res.data.code == "401" || res.data.code == 401) {
                    wx.login({
                        success: function (res) {
                            if (res.code) {
                                util.wxAjax("api/login/getToken", "POST", {
                                    "jsCode": res.code
                                }, function (res) {
                                    wx.setStorageSync("token", JSON.stringify(res.data.data));
                                });
                            }
                        }
                    });
                }
                callback(res);
            }
        }
    })
}

//时间戳转换成日期时间  
const js_date_time = (unixtime) => {
    var date = new Date(parseInt(unixtime));
    var year = date.getFullYear();
    var month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    var now = new Date();
    var now_new = Date.parse(now.toDateString());  //typescript转换写法  
    var milliseconds = now_new - date;
    var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    return timeSpanStr;
}

//将字符串格式时间分解为数组格式 time -- "2018-06-24 00:00"
const getTimeArr = time => {
    var temp = time.split(" ");
    var day = temp[0].split("-");
    var hours = temp[1].split(":");
    var timeArr = [];
    for (var i = 0; i < day.length; i++) {
        timeArr.push(day[i]);
    }
    for (var i = 0; i < hours.length; i++) {
        timeArr.push(hours[i]);
    }
    return timeArr;
}

//处理时间变成多少秒前，多少分钟前等等
const initTime = (time) => {
    var getDate = getTimeArr(time);
    var date = new Date(getDate[0], getDate[1] - 1, getDate[2], getDate[3], getDate[4], getDate[5]).getTime() / 1000;
    var now = parseInt(new Date().getTime() / 1000);
    if (now - date > 31104000) {
        return parseInt((now - date) / 60 / 60 / 24 / 30 / 12) + "年前";
    } else if (now - date > 2592000) {
        return parseInt((now - date) / 60 / 60 / 24 / 30) + "月前";
    } else if (now - date > 86400) {
        return parseInt((now - date) / 60 / 60 / 24) + "天前";
    } else if (now - date > 3600) {
        return parseInt((now - date) / 60 / 60) + "小时前";
    } else if (now - date > 60) {
        return parseInt((now - date) / 60) + "分钟前";
    } else {
        return now - date + "秒前";
    }
}

//去除html标签获取内容
const repalceHtml = (str) => {
    var dd = str.replace(/<\/?.+?>/g, "");
    // var content = dd.replace(/ /g, "");//dds为得到后的内容
    var content = dd.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    return content;
}

module.exports = {
    HEADER: HEADER,
    formatTime: formatTime,
    toDate: toDate,
    getFloatStr: getFloatStr,
    wxAjax: wxAjax,
    format: js_date_time,
    initTime: initTime,
    upload: upload,
    repalceHtml: repalceHtml
}
